package tcube.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CubeUtil {
	public static String HttpGetContent(URL url, String type)
			throws IOException, InterruptedException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod(type);
		connection.connect();

		int code = connection.getResponseCode();
		// int cnt = 1;
		System.out.println("Response code of the object is " + code);
		if (code == 200) {

			System.out.println("test....");
			
			String value = connection.getHeaderField("X-RateLimit-Remaining");
			if(value!=null){
				System.out.println("remain"+value);
				Integer remain = Integer.valueOf(value);
				if(remain<=15){
					Thread.sleep(600000);
				}
			}
			
			
//			for (int i = 0;; i++) {
//				String name = connection.getHeaderFieldKey(i);
//				String value = connection.getHeaderField(i);
//				
//				if (name == null && value == null) {
//					break;
//				}
//				if (name == null) {
//					System.out.println("Server HTTP version, Response code:");
//					System.out.println(value);
//					System.out.print("\n");
//				} else {
//					System.out.println(name + "=" + value);
//				}
//			}
			// String limit = connection.getHeaderField("X-RateLimit-Limit");
			// String remaining =
			// connection.getHeaderField("X-RateLimit-Remaining");
			// System.out.println("limit"+limit+"remain"+remaining);
			//
			// connection.disconnect();
			
			InputStreamReader in = new InputStreamReader(
					(InputStream) connection.getContent());
			BufferedReader buff = new BufferedReader(in);
			String s = "";
			String response = "";

			while ((s = buff.readLine()) != null) {
				response += s;
			}

			in.close();
			return response;

		}
		connection.disconnect();
		return null;
	}
}
